< previous page page_460 next page >

Page 460
Listing 20.6 Continued
Sub TestFindWindow()

    Const MAX_TEXT_SIZE = 50

    Dim hwndCurrent As Long
    Dim iCount As Integer
    Dim sClass As String
    Dim sCaption As String
    Dim lRetVal As Long

    iCount = 0
    hwndCurrent = FindWindow("Notepad", vbNullString)

    While hwndCurrent <> 0

        'Get the class name of the current Window
        sClass = Space$(MAX_TEXT_SIZE + 1)
        lRetVal = GetClassName(hwndCurrent, sClass, MAX_TEXT_SIZE)

        'If the Window is Notepad then increment count, print caption
        If Trim$(sClass) = "Notepad" & Chr$(0) Then
              iCount = iCount + 1
              sCaption = Space$(MAX_TEXT_SIZE + 1)
              lRetVal = GetWindowText(hwndCurrent, sCaption, MAX_TEXT_SIZE)
              Debug.Print Left$(sCaption, lRetVal)
        End If

        hwndCurrent = GetWindow(hwndCurrent, GW_HWNDNEXT)

    Wend

    Debug.Print "Number of open Notepad windows: " & iCount

End Sub
CAUTION
Take care to understand the role of null characters in API calls. In Listing 20.6, the GetClassName and GetWindowText API functions both put a Null on the end of the returned string. For this reason, I added a Null to the end of the word Notepad in the If statement so that the comparison would work. The Trim function removes spaces but not the ending Null. Another way to handle this dilemma is to use the return value of the GetClassName API with Left$ as follows:
If Left$(sClass,lRetVal) = "Notepad" Then . . . etc
In any case, it would probably behoove you to write a quick function to remove extra null values and trailing spaces from a given string.

Using the Window Handle
So now that you have gone to all the trouble of finding a window handle, what can you do with it? The answer is quite a bit. For starters, you can control the state of the window with the ShowWindow API:
lRetVal = ShowWindow(hwndNotepad, SW_SHOWMINIMIZED)

 
< previous page page_460 next page >